//
//  WBHomeController.swift
//  sinaWeibo
//
//  Created by 吴熠 on 16/11/12.
//  Copyright © 2016年 吴熠. All rights reserved.
//

import UIKit
import SVProgressHUD

private let cellID = "cellID"
private let retweetCellID = "retweet"

class WBHomeController: WBBaseTableViewController {

    
    //controller要引用viewModel
    lazy var homeViewModel : WBHomeViewModel = WBHomeViewModel()
    lazy var wbrefreshControl : WBRefreshControl = WBRefreshControl()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName:"navigationbar_pop" , target: self, action: #selector(push))
        
        if !userLogin{
            visitorView.upDateUI(title: "我追你,我,追到你,你就让我,嘿~嘿~嘿~", imageName: "visitordiscover_feed_image_smallicon", isHome: true)
            return;
        }
        
        setupTableView()
        
        loadData()
    
    }
    private func setupTableView(){
        let statusCellNib = UINib(nibName: "WBStatusCell", bundle: nil)
        
        tableView.register(statusCellNib, forCellReuseIdentifier: cellID)
        
        //注册转发微博的cell
        let retweetCellNib = UINib(nibName: "WBRetweetCell", bundle: nil)
        
        tableView.register(retweetCellNib, forCellReuseIdentifier: retweetCellID)
        
        //设置行高
//        tableView.rowHeight = 600
        tableView.separatorStyle = .none
        
        tableView.tableFooterView = indicatorView
        //实例化下拉刷新指示器
//        refreshControl = UIRefreshControl()
//        
//        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        //自定义下拉刷新控件
        self.view.addSubview(wbrefreshControl)
        wbrefreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        
        //添加提示lablel
        tipLabel.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 35)
        //设置y值
        tipLabel.frame.origin.y = 64-35
        //放在导航条下面
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: self.navigationController!.navigationBar)
        
        self.tableView.addSubview(refreshImg)
        refreshImg.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(self.tableView)
        };
        
        
    }
    
    func loadData(){
        homeViewModel.loadData(isPullup: indicatorView.isAnimating) { (isSuccess,count) in
            if !isSuccess {
                return
            }
            
            if self.indicatorView.isAnimating == false {
                self.startAnimation(count: count)
            }
            
            self.wbrefreshControl.endRefreshing()
            //停止转动
//            self.refreshControl?.endRefreshing()
            self.indicatorView.stopAnimating()
            
            
            self.tableView.reloadData()
            
        }
    }

    //提示显示多少条数据的动画
    private func startAnimation(count : Int){
        //如果tiplabel正在动画就直接返回
        if tipLabel.isHidden == false {
            return
        }
        let tipText = count == 0 ? "没有新微博" : "有\(count)条新鲜事"
        tipLabel.text = tipText
        //动画前显示tiplabel
        self.tipLabel.isHidden = false
        
        //动画开始前记录y值
        let y = self.tipLabel.frame.origin.y
        UIView.animate(withDuration: 1, animations: {
            self.tipLabel.frame.origin.y = 64
        }) { (_) in
            //再回去
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                self.tipLabel.frame.origin.y = y
            }, completion: { (_) in
                //完成动画后隐藏
                self.tipLabel.isHidden = true
            })
        }
        
    }

    
    private lazy var refreshImg : UIImageView = UIImageView(image: #imageLiteral(resourceName: "refreshbg"))
    
    //懒加载小菊花
    lazy var indicatorView : UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        //indicator.startAnimating()//测试是否开启菊花转动
        return indicator
    }()
    
    //实例化提示加载数据的控件UILabel
    private lazy var tipLabel : UILabel = {
        let lbl = UILabel(title: "", fontSize: 16, textColor: UIColor.white)
        //设置控件背景色
        lbl.backgroundColor = UIColor.orange
        //设置隐藏
        lbl.textAlignment = .center
        lbl.isHidden = true
        return lbl
    }()
    
    
    func push(){
        let demo = WBDemoController()
        demo.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(demo, animated: true)
        
    }

    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.homeViewModel.viewmodelArr.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let s = self.homeViewModel.viewmodelArr[indexPath.row]
        
        let ID = getCellID(viewModel: s)
        
        let cell = tableView.dequeueReusableCell(withIdentifier: ID, for: indexPath) as! WBStatusCell
//        cell.textLabel?.text = statusArr[indexPath.row].text
        cell.selectionStyle = .none
//        cell.textLabel?.text = s?.text
        cell.viewModel = s
        return cell
    }

    private func getCellID(viewModel : WBStatusViewModel)->String {
        return viewModel.status?.retweeted_status == nil ? cellID : retweetCellID
    }
    
    //自动行高的设置  协议方法
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //获取显示cell的模型数据
        let viewModel = self.homeViewModel.viewmodelArr[indexPath.row]
        //使用NSBundle的方式加载cell
        let name = nibName(viewModel: viewModel)
        //根据nibname加载cell
        let cell = UINib(nibName: name, bundle: nil).instantiate(withOwner: nil, options: nil).last as! WBStatusCell
        
        //给cell绑定要显示的数据
        cell.viewModel = viewModel
        
        cell.layoutIfNeeded()
        //返回cell里最下面的toolBar的最大Y值
        return cell.toolBar.frame.maxY
    }
    
    func nibName(viewModel:WBStatusViewModel)->String{
        return viewModel.status?.retweeted_status == nil ? "WBStatusCell" : "WBRetweetCell"
    }

    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indicatorView.isAnimating==false && indexPath.row == self.homeViewModel.viewmodelArr.count-2 {
            //满足条件小菊花开始转,然后加载数据
            indicatorView.startAnimating()
//            self.homeViewModel.viewmodelArr = 
            //请求更多数据
            loadData()
        }
    }
    

}


